package com.example.xyxwebbackend001.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.xyxwebbackend001.mapper.*;
import com.example.xyxwebbackend001.model.DTO.TPostsDTO;
import com.example.xyxwebbackend001.model.entity.*;
import com.example.xyxwebbackend001.query.UserQueryCondition;
import com.example.xyxwebbackend001.service.ComService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ComServiceImpl implements ComService {

    @Autowired
    private TPostsxMapper tPostsxMapper;
    @Autowired
    private LikesMapper likesMapper;
    @Autowired
    private FavoriteMapper favoriteMapper;

    @Autowired
    private TCommentMapper tCommentMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

@Override
public List<TPostsDTO> getTPostList(Integer Id, String cityId) {
    UserInfo userInfo  = userInfoMapper.getUserInfoList(Id);
    UserQueryCondition condition = new UserQueryCondition();
    String tags = Arrays.stream(userInfo.getInterestedCulture().split(","))
            .map(t -> "'" + t.trim() + "'")
            .collect(Collectors.joining(","));
    condition.setTags(tags);
    condition.setPlace(cityId);

    QueryWrapper<TPosts> wrapper = new QueryWrapper<>();
    for (UserQueryCondition.SortField field : condition.getSortFields()) {
        if (field.getValues() != null) {
            wrapper.orderByDesc("FIELD(" + field.getKey() + ", " + field.getValues() + ")");
        } else {
            wrapper.orderByDesc(field.getKey());
        }
    }
    return tPostsxMapper.getTPostsList(Id, wrapper);
}

    @Override
    public Map<String, Object> getUserPostStats(Integer userId) {
        List<Integer> postIds = tPostsxMapper.selectPostIdsByUserId(userId);
        if (postIds == null || postIds.isEmpty()) {
            return Map.of(
                    "worksCount", 0,
                    "totalLikes", 0,
                    "totalFavorites", 0
            );
        }

        return Map.of(
                "worksCount", postIds.size(),
                "totalLikes", likesMapper.sumLikesByPostIds(postIds),
                "totalFavorites", favoriteMapper.sumFavoritesByPostIds(postIds)
        );
    }

    @Override
    public boolean toggleAction(String actionType, Integer postId) {
        Integer userId = StpUtil.getLoginIdAsInt();

        switch (actionType.toLowerCase()) {
            case "like":
                return handleLikeToggle(userId, postId);
            case "favorite":
                return handleFavoriteToggle(userId, postId);
            default:
                throw new IllegalArgumentException("无效的操作类型");
        }
    }

    @Override
    public boolean handleLikeToggle(Integer userId, Integer postId) {
        QueryWrapper<Likes> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("t_post_id", postId);

        boolean exists = likesMapper.exists(wrapper);
        if (exists) {
            likesMapper.delete(wrapper);
            return false;
        } else {
            Likes like = new Likes();
            like.setUserId(userId);
            like.setTPostId(postId);
            like.setTLikedAt(LocalDateTime.now());
            likesMapper.insert(like);
            return true;
        }
    }

    @Override
    public boolean handleFavoriteToggle(Integer userId, Integer postId) {
        QueryWrapper<Favorites> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("t_post_id", postId);

        boolean exists = favoriteMapper.exists(wrapper);
        if (exists) {
            favoriteMapper.delete(wrapper);
            return false;
        } else {
            Favorites fav = new Favorites();
            fav.setUserId(userId);
            fav.setTPostId(postId);
            fav.setTFavoritedAt(LocalDateTime.now());
            favoriteMapper.insert(fav);
            return true;
        }
    }

    @Override
    public boolean createComment(Integer postId, Integer userId, String content) {
        TPosts post = tPostsxMapper.selectByTPostId(postId);
        if (tPostsxMapper.selectByTPostId(postId) == null) {
            throw new IllegalArgumentException("无效的帖子ID");
        }

        TComment comment = new TComment();
        comment.setTPostId(postId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setTCreatedAt(LocalDateTime.now());

        return tCommentMapper.insert(comment) > 0;
    }

    @Override
    public boolean deleteComment(Integer commentId) {
        Integer currentUserId = StpUtil.getLoginIdAsInt();

        TComment comment = tCommentMapper.selectById(commentId);
        if (comment == null) {
            throw new IllegalArgumentException("评论不存在");
        }

        if (!comment.getUserId().equals(currentUserId)) {
            throw new IllegalArgumentException("无权删除他人评论");
        }

        return tCommentMapper.deleteById(commentId) > 0;
    }

    @Override
    public boolean createPost(TPosts post) {
        return tPostsxMapper.insert(post) > 0;
    }

    @Override
    public int cleanupExpiredDrafts() {
        return tPostsxMapper.delete(new QueryWrapper<TPosts>()
                .apply("(title = '' OR title IS NULL)")
                .apply("(content = '' OR content IS NULL)")
                .apply("(image_path = '' OR image_path IS NULL)")
                .le("created_at", LocalDateTime.now().minusMinutes(30))
        );
    }

    @Override
    public boolean updatePost(Integer tPostId, String title, String content, String imagePath,String place, String tags) {
        int count = tPostsxMapper.updatePost(tPostId, title, content, imagePath, place, tags);
        return count > 0;
    }
}
